package org.jdsm.flow.contact.impl.objectify.dao;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import org.jdsm.flow.contact.IContactEntity;
import org.jdsm.flow.contact.IContactFeedBack;
import org.jdsm.flow.contact.dao.IContactDAO;
import org.jdsm.flow.contact.impl.objectify.ContactEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;

/**
 * User: mikom
 * Date: 2/6/13
 * Time: 4:56 PM
 */
public class ContactDAO implements IContactDAO {
    private static final Logger log = LoggerFactory.getLogger(ContactDAO.class);
    @Resource
    private ObjectifyFactory objectifyFactory;

    private Objectify ofy(){
        return objectifyFactory.begin();
    }

    @Override
    public List<IContactEntity> getContacts() {
        return (List)ofy().load().type(ContactEntity.class).list();
    }

    @Override
    public void addContact(IContactEntity contactEntity) {
        ofy().save().entity(contactEntity).now();
        log.debug("contact entity {} was saved", contactEntity);
    }

    @Override
    public IContactEntity loadContact(IContactEntity entity){
        log.debug("try to load contact entity:{}", entity);
        return ofy().load().type(ContactEntity.class).id((Long) entity.getId()).get();
    }

    @Override
    public void saveFeedBack(IContactFeedBack feedBack){
        ofy().save().entity(feedBack).now();
        log.debug("feed back {} was saved", feedBack);
    }

    @Override
    public void removeContact(IContactEntity entity) {
        ofy().delete().entity(entity).now();
        log.debug("contact entity: {} was removed");
    }
}
